package com.wanwu.channel.service.strategy;

import com.wanwu.channel.common.enums.ExceptionEnum;
import com.wanwu.channel.common.enums.PayType;
import com.wanwu.channel.common.enums.TradeStatusEnum;
import com.wanwu.channel.common.exception.SystemException;
import com.wanwu.channel.common.util.DateUtils;
import com.wanwu.channel.converter.PayStatusConvert;
import com.wanwu.channel.dao.entity.ChannelMerchantInfoEntity;
import com.wanwu.channel.dto.vo.PayQueryStrategyReqVo;
import com.wanwu.channel.dto.vo.PayQueryStrategyRespVo;
import com.wanwu.channel.dto.vo.PrepayStrategyReqVo;
import com.wanwu.channel.remote.allinpay.config.TongLianConfig;
import com.wanwu.channel.remote.allinpay.http.TongLianHttp;
import com.wanwu.channel.remote.allinpay.http.req.TLPrepayReq;
import com.wanwu.channel.remote.allinpay.http.req.TLQueryReq;
import com.wanwu.channel.remote.allinpay.http.resp.TLH5payResp;
import com.wanwu.channel.remote.allinpay.http.resp.TLQueryResp;
import com.wanwu.channel.service.strategy.domain.PrepayStrategyResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @version v1.0
 * @ProjectName: channel
 * @ClassName: TongLianH5PayStrategy
 * @Description: 通联H5支付     对接文档：https://aipboss.allinpay.com/know/devhelp/main.php?pid=38
 * @Author: huangdh
 * @Date: 2020/4/11 上午11:54
 */
@Component
public class TongLianH5PayStrategy extends TongLianPayStrategy {

    @Resource
    private TongLianHttp tongLianHttp;

    @Resource
    private TongLianConfig tongLianConfig;

    private static Logger logger = LoggerFactory.getLogger(TongLianH5PayStrategy.class);

    /**
     * 通联H5支付下单
     *
     * @param payType 传入需要的支付方式
     * @param req     其他额外需要的参数
     * @return
     */
    @Override
    public PrepayStrategyResponse generatePayParams(PayType payType, PrepayStrategyReqVo req) {
        ChannelMerchantInfoEntity entity = req.getChannelMerchantInfoEntity();
        PrepayStrategyResponse response = new PrepayStrategyResponse();
        TLPrepayReq tlPrepayReq = new TLPrepayReq();
        tlPrepayReq.setTrxAmt(req.getPayAmount().toPlainString());
        tlPrepayReq.setReqSn(req.getBizOrderNo());
        tlPrepayReq.setBody(req.getOrderName());
        //有效时间固定为10分钟
        tlPrepayReq.setValidTime("10");
        String notifyUrl = tongLianConfig.getNotifyUrl();
        if (null != entity) {
            notifyUrl = notifyUrl + "/" + entity.getPayChannel() + "/" + entity.getBizCode() + "/" + entity.getMerchantNo();
        }
        tlPrepayReq.setNotifyUrl(notifyUrl);
        tlPrepayReq.setCusId(req.getCusId());
        tlPrepayReq.setAppId(req.getAppId());
        tlPrepayReq.setVersion("12");
        tlPrepayReq.setCharset("UTF-8");
        //附加订单备注信息
        tlPrepayReq.setRemark(req.getAttach());
        tlPrepayReq.setReturl(req.getMerPageUrl());
        tlPrepayReq.setChannelMerchantInfoEntity(entity);
        try {
            TLH5payResp tlh5payResp = tongLianHttp.h5pay(tlPrepayReq);
            response.setTradeStatus(TradeStatusEnum.SUCCESS);
            response.setPrepayReq(tlh5payResp.getPrePayReq());
            response.setMWebUrl(tlh5payResp.getMWebUrl());
        } catch (Exception e) {
            response.setTradeStatus(TradeStatusEnum.FAIL);
            if (e instanceof SystemException) {
                SystemException ex = (SystemException) e;
                response.setErrorMsg(ex.getMsg());
                response.setErrorCode(ex.getCode());
            } else {
                response.setErrorCode(ExceptionEnum.E10000.name());
                response.setErrorMsg(ExceptionEnum.E10000.getMsg());
            }
        }
        return response;
    }

    /**
     * 支付结果查询
     *
     * @param payType
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public PayQueryStrategyRespVo queryPayHttp(PayType payType, PayQueryStrategyReqVo request) {
        PayQueryStrategyRespVo response = new PayQueryStrategyRespVo();
        TLQueryReq req = new TLQueryReq();
        req.setReqSn(0 == request.getThirdFlag() ? request.getBizOrderNo() : request.getChannelNo());
        req.setTrxId(request.getTrxId());
        req.setCusId(request.getMerchantNo());
        req.setAppId(request.getMerchantAppId());
        req.setChannelMerchantInfoEntity(request.getChannelMerchantInfoEntity());
        TLQueryResp resp = tongLianHttp.query(req);
        //返回结果处理
        String trxStatus = resp.getTrxStatus();
        //调用结果成功，如果调用失败，底层已经抛了异常了，这里默认成功
        response.setChannelPayStatus(PayStatusConvert.tonglianConvert(trxStatus));
        response.setAcct(resp.getAcct());

        //根据上送标识将reqSn赋值给相应的字段
        if (0 == request.getThirdFlag()) {
            response.setBizOrderNo(resp.getReqSn());
        } else {
            response.setChannelNo(resp.getReqSn());
        }
        response.setTlOrderNo(resp.getTrxId());
        response.setThirdOrderNo(resp.getChannelTrxId());
        //新申请上送渠道单号
        response.setThirdFlag(1);
        if ("0000".equals(trxStatus)) {
            //业务结果成功
            response.setFinishTime(DateUtils.formatDate(8, resp.getFinTime()));
            response.setFeeAmount(StringUtils.isEmpty(resp.getFee()) ? "0" : resp.getFee());
            //海关总署-通联H5支付方式返回报文，落的是查询或者回调报文终态
            response.setQueryResp(resp.getQueryResp());
        } else if (StringUtils.isEmpty(trxStatus) || "2008".equals(trxStatus) || "2000".equals(trxStatus)) {
            //业务处理中，不需要更新，直接返回处理中
            response.setErrCode(trxStatus);
            response.setErrMsg("通联支付处理中");
        } else {
            //业务结果失败
            response.setErrCode(trxStatus);
            response.setErrMsg(resp.getErrorMsg());
        }
        return response;
    }

}
